﻿using SmartSapce.ServiceLocation;
using SmartSpace.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

namespace SmartSpace.WebApp._console.page
{
    public partial class page_design : System.Web.UI.Page
    {
        private Guid _pageId { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);
        }

        protected override void OnPreLoad(EventArgs e)
        {
            base.OnPreLoad(e);
        }

        protected override void OnPreInit(EventArgs e)
        {
            _pageId = new Guid(Request.QueryString["id"]);
            ICoreService service = ServiceLocator.Get<ICoreService>();
            DynamicPage page = service.GetPage(_pageId);

            _ctlPanel.Controls.Add(this.LoadControl("~/_templates/_page/" + page.TemplateName + ".ascx"));

            (CatalogZone1.Controls[0] as DeclarativeCatalogPart).WebPartsTemplate = new CategoryTemplate(this, _ctlWebPartManager);
            
            base.OnPreInit(e);
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
        }

        protected override void FrameworkInitialize()
        {
            base.FrameworkInitialize();
        }

        protected void _ctlBtnEdit_Click(object sender, EventArgs e)
        {
            _ctlWebPartManager.DisplayMode = WebPartManager.EditDisplayMode;
        }

        protected void _ctlBtnCategory_Click(object sender, EventArgs e)
        {
            _ctlWebPartManager.DisplayMode = WebPartManager.CatalogDisplayMode;
        }
    }

    public class CategoryTemplate : ITemplate
    {
        public Page _page;
        private WebPartManager _webPartManager;

        public CategoryTemplate(Page page, WebPartManager webPartManager)
        {
            _page = page;
            _webPartManager = webPartManager;
        }

        public void InstantiateIn(Control container)
        {
            ICoreService service = ServiceLocator.Get<ICoreService>();
            PagedList<Module> modules = service.GetModules("_webpart", 0, 999);

            foreach (var module in modules)
            {
                foreach (var view in module.Views)
                {
                    Control control = _page.LoadControl(view.Name);
                    control.ID = view.Id.ToString();

                    WebPart part = _webPartManager.CreateWebPart(control);
                    part.Title = view.Caption;
                    part.Description = view.Caption;
                    container.Controls.Add(part);
                }
            }
        }
    }
}